package com.demo.sentinel.command;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.Semaphore;


/**
 * @ClassName Desasdf
 * @Description TODO
 * @Author hf
 * @Date 2023/2/6 9:56
 * @Version 1.0
 */
public class TestCd {

    static class Plager implements Runnable {
        private Integer index;

        public Plager(Integer index) {
            this.index = index;
        }

        @Override
        public void run() {
            System.out.println("玩家" + index + "准备完毕");
            countDownLatch.countDown();
        }
    }


    static class Monster implements Runnable {
        private Integer index;

        public Monster(Integer index) {
            this.index = index;
        }

        @Override
        public void run() {
            System.out.println("怪物" + cyclicBarrier.getNumberWaiting() + "号被消灭");
        }
    }



    static class Worker implements Runnable {
        private Integer index;

        public Worker(Integer index) {
            this.index = index;
        }

        @Override
        public void run() {
            try {
                semaphore.acquire();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("工人" + index + "占用了一个机器正在工作");
            semaphore.release();
        }
    }

    private static CountDownLatch countDownLatch = new CountDownLatch(5);
    private static CyclicBarrier cyclicBarrier = new CyclicBarrier(5);
    private static Semaphore semaphore = new Semaphore(5);

    public static void main(String[] args) throws InterruptedException, BrokenBarrierException {
        for (int i = 0; i < 5; i++) {
            Plager plager = new Plager(i);
            new Thread(() -> {
                plager.run();
            }).start();
        }
        countDownLatch.await();
        System.out.println("玩家准备完毕，开始游戏");


        for (int i = 0; i < 5; i++) {
            Monster monster = new Monster(i);
            new Thread(() -> {
                monster.run();
            }).start();
        }
        System.out.println("所有怪物都被消灭，游戏进入第二阶段!");


        for (int i = 0; i < 8; i++) {
            Worker worker = new Worker(i);
            new Thread(() -> {
                worker.run();
            }).start();
        }




    }
}
